package com.dianneng.show.http;

import android.content.Context;
import android.text.TextUtils;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.dianneng.show.util.ACache;
import com.dianneng.show.util.Constant;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * This class initializes retrofit with a defaulticon configuration.
 * You can use this class to initialize the different services.
 */

public class RetrofitHelper {

    public static final String baseUrl = "http://47.99.213.211:8080/x_springboot/app/";
    private static Context mContext;

    public UserInfoService getUserInfoService() {
        final Retrofit retrofit = createRetrofit();
        return retrofit.create(UserInfoService.class);
    }


    /**
     * This custom client will append the "username=demo" query after every request.
     */
    private OkHttpClient createOkHttpClient() {
        final OkHttpClient.Builder httpClient =
                new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                final Request original = chain.request();
                final HttpUrl originalHttpUrl = original.url();
                final HttpUrl url = originalHttpUrl.newBuilder()
                        .build();
                //去除空参数
                FormBody newBody = null;
                if (original.body() instanceof FormBody) {
                    FormBody formBody = (FormBody) original.body();
                    FormBody.Builder builder = new FormBody.Builder();
                    for (int i = 0; i < formBody.size(); i++) {
                        //@FieldMap 注解 Map元素中 key 与 value 皆不能为null,否则会出现NullPointerException
                        if (!TextUtils.isEmpty(formBody.value(i)))
                            builder.add(formBody.name(i), formBody.value(i));
                    }
                    newBody = builder.build();
                }
                //去除url里的空参数
                HttpUrl.Builder builder = url.newBuilder();
                Set<String> queryKeyName = url.queryParameterNames();
                for (String s : queryKeyName) {
                    List<String> list = url.queryParameterValues(s);
                    if (list.isEmpty() || TextUtils.isEmpty(list.get(0))) {
                        builder = builder.removeAllQueryParameters(s);
                    }
                }
                final HttpUrl newUrl = builder.build();
                // Request customization: add request headers
                final Request.Builder requestBuilder = original.newBuilder()
                        .url(newUrl);
                requestBuilder.addHeader("Administrator", "MIMIMI");
                requestBuilder.addHeader("Device", "Android");
                if (!TextUtils.isEmpty(ACache.get(mContext).getAsString(Constant.TOKEN)))
                    requestBuilder.addHeader("Authorization", ACache.get(mContext).getAsString(Constant.TOKEN));
                requestBuilder.addHeader("VersionName", AppUtils.getAppVersionName());
                requestBuilder.addHeader("VersionCode", AppUtils.getAppVersionCode() + "");
                requestBuilder.addHeader("SystemVersion", DeviceUtils.getSDKVersion() + "");
                if (!TextUtils.isEmpty(DeviceUtils.getModel()))
                    requestBuilder.addHeader("SystemModel", DeviceUtils.getModel());
                if (!TextUtils.isEmpty(DeviceUtils.getManufacturer()))
                    requestBuilder.addHeader("DeviceBrand", DeviceUtils.getManufacturer());
                requestBuilder.addHeader("MAC", DeviceUtils.getMacAddress());
                if (original.body() instanceof FormBody) {
                    final Request request = requestBuilder.post(newBody).build();
                    return chain.proceed(request);
                } else {
                    final Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            }
        });

        return httpClient.build();
    }

    /**
     * Creates a pre configured Retrofit instance
     */
    private Retrofit createRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // <- add this
                .client(createOkHttpClient())
                .build();
    }

    public static RetrofitHelper getHelper(Context context) {
        mContext = context;
        return H.mRetrofitHelper;
    }

    private RetrofitHelper() {
    }

    private static class H {
        private static final RetrofitHelper mRetrofitHelper = new RetrofitHelper();
    }
}